<template>
  <div v-loading="fileLoading">
    <div style="height: 360px;width: 714px;overflow: auto;">
      <el-table :data="investorFileList" border class="nowrapTable formTable">
        <el-table-column :label="$t('文件名称')" align="center" prop="name">
          <template slot-scope="scope">
            <thumbnail :file-data="scope.row" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('出资人')" align="center" prop="lpId">
          <template slot-scope="scope">
            <el-select v-model="scope.row.lpId" filterable :placeholder="$t('请选择出资人')" @change="onChange($event, scope.row)">
              <el-option
                v-for="item in lpOptions"
                :key="item.lpId"
                :label="item.userName"
                :value="item.lpId"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" width="60px">
          <template slot-scope="scope">
            <el-button size="small" type="text" icon="el-icon-delete" @click="delRow(scope.$index)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="position: absolute; bottom: 0; font-size: 14px;color: #babebe">{{ $t('文件名中包含出资人全称或简称时将自动匹配') }}</div>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <uploader
        ref="uploader"
        :options="options"
        :auto-start="true"
        class="uploader-app"
        style="float: left;margin-right: 10px;"
        @file-added="onFileAdded"
        @file-progress="onProgress"
        @file-error="onError"
        @file-success="onFileSuccess"
      >
        <uploader-btn
          id="global-uploader-btn"
          ref="uploadBtn"
          style="font-weight: 500;border-radius: 4px;border: 1px solid;"
          :attrs="attrs"
        >{{ $t('批量上传') }}</uploader-btn>
      </uploader>
      <el-button style="float: left;" @click="cancel">{{ $t('取消') }}</el-button>
      <el-button type="primary" style="float: left;" @click="submitForm">{{ $t("完成") }}</el-button>
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { config } from '@/utils'
import { findLpBaseList } from '@/api/fund/lpBase/lpBase'
import { ACCEPT_CONFIG } from '@/utils/config'
import { fileBaseMerging } from '@/api/file/fileBase'
import SparkMD5 from 'spark-md5'
import $ from 'jquery'
import jsMd5 from 'js-md5'
export default {
  props: {
    lpList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      form: { lpId: '' },
      rules: {
        lpId: [{ required: true, message: this.$t('请选择出资人'), trigger: 'change' }]
      },
      fileLoading: false,
      investorFileList: [],
      // 添加出资人附件窗口
      addFilesOpen: false,
      lpBaseArray: [],
      lpOptions: [],
      options: {
        target: config.baseURL + '/file/fileBase/uploadDocLib?dataType=lp_bulletin_investor',
        chunkSize: '2048000',
        singleFile: false,
        fileParameterName: 'file',
        maxChunkRetries: 3,
        testChunks: false, // 是否开启服务器分片校验
        // 服务器分片校验函数，秒传及断点续传基础
        checkChunkUploadedByResponse: function(chunk, message) {
          const objMessage = JSON.parse(message)
          if (objMessage.data !== null && objMessage.data.numbers !== null) {
            return (JSON.parse(objMessage.data.numbers) || []).indexOf(chunk.offset + 1) >= 0
          } else {
            return false
          }
        },
        headers: {
          Authorization: getToken()
        },
        query() {}
      },
      attrs: {
        accept: ACCEPT_CONFIG.getAll()
      }
    }
  },
  methods: {
    onChange(e, row) {
      // console.log(e, row)
      delete row.lpId
      this.$set(row, 'lpId', e)
      this.$forceUpdate()
    },
    init(fundId) {
      this.lpOptions = []
      var arr = []
      if (this.lpList.length > 0) {
        this.lpList.forEach(item => {
          // 出资人下拉列表
          this.lpOptions.push({ lpId: item.lpId, userName: item.userName })
          // 整理所有出资人附件
          if (item.fileList && item.fileList.length > 0) {
            item.fileList.forEach(file => {
              // file.lpId = item.lpId
              this.$set(file, 'lpId', item.lpId)
              arr.push(file)
            })
          }
        })
      }
      this.investorFileList = arr
      // 获取传来的出资人的全称简称
      if (this.lpOptions.length > 0) {
        findLpBaseList({ fundId: fundId }).then(response => {
          this.lpBaseArray = response.rows
        })
      }
    },
    onError(error, file, fileList) {
      this.msgError(this.$t('上传失败, 请检查附件是否合法!'))
      console.log(error, file, fileList)
    },
    onFileAdded(file) {
      // 设置文件md5
      this.computeMD5(file)
    },
    /**
     * 计算md5，实现断点续传及秒传
     * @param file
     */
    computeMD5(file) {
      const fileReader = new FileReader()
      // const time = new Date().getTime()
      const blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
      let currentChunk = 0 // 当前分片
      const chunkSize = 10 * 1024 * 1000
      const chunks = Math.ceil(file.size / chunkSize) // 计算该文件一共有多少个分片
      const spark = new SparkMD5.ArrayBuffer() // 创建一个spark md5计算arrayBuffer的对象
      // 文件状态设为"计算MD5"
      file.pause()
      loadNext() // 首次读取文件分片
      // debugger
      // 当前分片读取完成
      fileReader.onload = e => {
        // debugger
        spark.append(e.target.result)
        if (currentChunk < chunks) {
          currentChunk++
          loadNext()
          // 实时展示MD5的计算进度
          this.$nextTick(() => {
            $(`.myStatus_${file.id}`).text('校验MD5 ' + ((currentChunk / chunks) * 100).toFixed(0) + '%')
          })
        } else {
          // 最后一个分片，结束
          file.uniqueIdentifier = spark.end() + '_' + jsMd5(file.name)
          file.resume()
        }
      }
      fileReader.onerror = function() {
        this.error(this.$t('文件读取出错，请检查文件'))
        file.cancel()
      }
      function loadNext() { // 读取文件分片
        const start = currentChunk * chunkSize // 切片起始位置
        const end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize // 切片终止位置
        fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end)) // fileReader读取下一个文件分片
      }
    },
    onProgress(event, file, fileList) {
      this.fileLoading = true
      console.log(event, file, fileList)
    },
    onFileSuccess(rootFile, file, response) {
      console.log(rootFile, file, response)
      this.fileLoading = true
      const res = JSON.parse(response)
      if (res.data !== null) {
        // console.log(file.name + '文件上传阶段: ' + res.data.status + ',该文件存在的块数有: ' + JSON.parse(res.data.numbers))
        // 判断块是否全了. 不全的话重新上传
        if (JSON.parse(res.data.numbers).length === file.chunks.length) {
          this.callbackMerge(file)
        } else {
          console.log(file.name + '文件上传阶段: ' + res.data.status + ',该文件存在的块数有: ' + JSON.parse(res.data.numbers))
          file.bootstrap()
          file.retry()
        }
      } else {
        // 发生未知错误, 清理列表. (较大可能存在的原因:不同用户, 同一时间上传了MD5相同的附件)
        rootFile.clean()
      }
    },
    /**
     * 回调合并, 调用后台接口, 使其合并该文件
     * @param file
     */
    callbackMerge(file) {
      // 调用后台, 处理文件合并
      fileBaseMerging({
        identifier: file.uniqueIdentifier,
        dataType: 'lp_bulletin_investor',
        totalSize: file.size,
        originalFilename: file.name,
        totalChunks: file.chunks.length,
        fileId: this.fileId
      }).then(res => {
        // 当前文件全部上传完成
        this.$bus.$emit('fileSuccess')
        if (this.investorFileList === undefined) {
          this.investorFileList = []
        }
        var row = { id: res.data.fileId, name: res.data.fileName }
        var lpData = this.lpBaseArray.find(lp =>
          (res.data.fileName.toLocaleLowerCase().includes((lp.userName === undefined || lp.userName === null) ? '-000-000-' : lp.userName.toLocaleLowerCase()))
        )
        if (!lpData) {
          lpData = this.lpBaseArray.find(lp =>
            (res.data.fileName.toLocaleLowerCase().includes((lp.shortName === undefined || lp.shortName === null) ? '-000-000-' : lp.shortName.toLocaleLowerCase()))
          )
        }
        if (lpData) {
          row.lpId = lpData.lpId
        }
        this.investorFileList.push(row)
        this.fileLoading = false
      }).catch(e => {
        console.error('文件合并回调失败!', e)
      })
    },
    delRow(index) {
     this.investorFileList.splice(index, 1)
    },
    submitForm() {
      if (this.investorFileList.length >= 0) {
        var flag = true
        this.investorFileList.forEach(item => {
          if (item.lpId === undefined || item.lpId === null || item.lpId === '') {
            this.msgError(this.$t('请选择出资人'))
            flag = false
          }
        })
        if (flag) {
          this.$emit('autoUploadFileEnd', this.investorFileList)
          this.cancel()
        }
      } else {
        this.cancel()
      }
    },
    cancel() {
      this.$parent.$parent.autoUploadOpen = false
    }
  }
}
</script>

<style scoped>

</style>
